const router = require("koa-router")();
const swaggerJSDoc = require("swagger-jsdoc");
const { koaSwagger } = require("koa2-swagger-ui");
const { options, getServers } = require("../config/swagger.config");

// 动态生成 swagger 文档
router.get("/swagger.json", async (ctx) => {
  // 根据请求动态设置服务器列表
  const dynamicOptions = {
    ...options,
    definition: {
      ...options.definition,
      servers: getServers(ctx.req),
    },
  };
  const spec = swaggerJSDoc(dynamicOptions);
  ctx.set("Content-Type", "application/json");
  ctx.body = spec;
});

// swagger-ui
router.get(
  "/swagger",
  koaSwagger({
    routePrefix: false, // 禁用路由前缀
    swaggerOptions: {
      url: "/swagger.json",
    },
    exposeSpec: true,
    hideTopbar: true,
  })
);

module.exports = router;
